[LeetCode 01]Two Sum 两数之和
Problem decription:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
1 | Given nums = [2, 7, 11, 15], target = 9, |
题目描述:
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
1 | 给定 nums = [2, 7, 11, 15], target = 9 |
Solution:
- 排序数组,用两个头尾指针遍历即可,排序复杂度为O(nlogn),空间复杂度为O(1);
利用map,以<值,数组下标>方式储存,再遍历数组即可;
这里采用第二种解法,要注意考虑数组中包含重复值的情况,在加入map的过程中要做判断;
Code:
1 | import java.util.HashMap; |